# 工具函数 #

import datetime
import random
import time

from db.db import db
from db.models import (DriversServiceTable, DriverTable, OrderTable,
                       StatesTable, TimesTable, SimulationTable, TDTable)


def random_choice_state(states_id_start, states_id_end):
    """
    功能：给定起点和终点状态ID，随机挑选状态
    输入：起点状态ID，终点状态ID
    输出：状态ID
    """
    state_start = StatesTable.query.filter_by(gid=states_id_start).first()
    state_end = StatesTable.query.filter_by(gid=states_id_end).first()
    # 获取行列索引随机数
    row_max = max([state_start.row, state_end.row])
    row_min = min([state_start.row, state_end.row])
    column_max = max([state_start.column, state_end.column])
    column_min = min([state_start.column, state_end.column])
    row = random.randint(row_min, row_max)
    column = random.randint(column_min, column_max)
    # 获取状态
    state = StatesTable.query.filter_by(row=row, column=column).first()
    return state.gid


def getDispatchValue(startStateID, endStateID):
    """
    功能：获取派单值
    输入：起点状态ID, 终点状态ID
    输出：派单值
    """
    startState = StatesTable.query.filter_by(gid=startStateID).first()
    endState = StatesTable.query.filter_by(gid=endStateID).first()
    dispatchValue = 0.7 * startState.value + 0.3 * endState.value
    return dispatchValue


def getStateIDs(centerStateID):
    """
    功能：获取3*3窗口状态ID
    输入：中心状态ID
    输出：3*3窗口状态ID
    """
    centerState = StatesTable.query.filter_by(gid=centerStateID).first()
    states = None
    bottom = centerState.row - 1
    if bottom == -1:
        bottom = 0
    top = centerState.row + 1
    if top == 39:
        top = 38
    left = centerState.column - 1
    if left == -1:
        left = 0
    right = centerState.column + 1
    if right == 38:
        right = 37
    states = StatesTable.query.filter(StatesTable.column.between(left,right))\
        .filter(StatesTable.row.between(bottom, top))\
        .with_entities(StatesTable.gid).all()  # 结果含有元组
    # 取出数据
    for i in range(len(states)):
        states[i] = states[i][0]
    return states